package com.tv.cms.system.operator.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.tv.cms.goods.model.Goods;
import com.tv.cms.payorderinfo.model.PayOrderInfo;
import com.tv.cms.system.account.model.Account;
import com.tv.cms.system.account.service.AccountService;
import com.tv.cms.system.admin.model.Admin;
import com.tv.cms.system.admin.service.AdminService;
import com.tv.cms.system.operator.model.Operator;
import com.tv.cms.system.operator.model.OperatorConfig;
import com.tv.cms.system.operator.service.OperatorConfigService;
import com.tv.cms.system.operator.service.OperatorService;
import com.tv.cms.system.operator.model.Operator;
import com.tv.cms.utils.Result;
import com.tv.cms.utils.ResultCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * TODO
 *
 * @author
 * @date
 **/
@RestController
@RequestMapping("operator")
public class OperatorController {
    @Resource
    private OperatorService service;
    @Resource
    private AdminService adminService;
    @Resource
    private OperatorConfigService operatorConfigService;
    @Resource
    private AccountService accountService;
    
    @PostMapping("list")
    public Result<Page<Operator>> list(@RequestBody Operator operator){
        Admin admin = adminService.getById(StpUtil.getLoginIdAsInt());
        MPJLambdaWrapper<Operator> wrapper = new MPJLambdaWrapper<Operator>()
                .selectAll(Operator.class)
                .selectAs("t1.user_name", Operator:: getCreateName)
                .leftJoin(Admin.class, Admin :: getId, Operator :: getCreateBy)
                .selectAs("t2.user_name", Operator:: getUpdateName)
                .leftJoin(Admin.class, Admin :: getId, Operator :: getUpdateBy)
                .selectAs("t3.name", Operator:: getPName)
                .leftJoin(Operator.class, Operator :: getId, Operator :: getParentId)
                .selectAs("t4.balance", Operator:: getBalance)
                .selectAs("t4.three", Operator:: getThreeSub)
                .selectAs("t4.seven", Operator:: getSevenSub)
                .selectAs("t4.thirty", Operator:: getThirtySub)
                .leftJoin(Account.class, Account :: getOperatorId, Operator :: getId)
                .like(StringUtils.hasText(operator.getName()), Operator :: getName, operator.getName())
                .eq(operator.getStatus() != null,  Operator :: getStatus,operator.getStatus())
               // .eq(admin.getRoleId() == 3 || admin.getRoleId() == 5,  Operator :: getParentId,admin.getOperatorId())
                .eq(admin.getRoleId() != 1, Operator :: getCreateBy,StpUtil.getLoginIdAsInt())
                .orderByDesc(Operator :: getStatus,Operator :: getCreateTime);
        Page<Operator> page = service.selectJoinListPage(new Page<>(operator.getPage(), operator.getLimit()), Operator.class, wrapper);
        Result<Page<Operator>> result = new Result<>();
        return result.OKDATA(page);
    }

    @PostMapping("save")
    public Result<Object> save(@RequestBody Operator operator){
        if(!StringUtils.hasText(operator.getName())){
            return Result.FAILURE(400,"参数错误");
        }
        Operator one = service.getOne(new QueryWrapper<Operator>().eq("name", operator.getName()));
        if(one != null && operator.getId() == null){
            return Result.FAILURE("经销商已存在");
        }
        if(one != null && operator.getId() != null && !Objects.equals(operator.getId(), one.getId())){
            return Result.FAILURE("经销商已存在");
        }
        boolean b;
        Admin admin = adminService.getById(StpUtil.getLoginIdAsInt());
        if(admin.getRoleId() == 3 || admin.getRoleId() == 5){
            operator.setParentId(admin.getOperatorId());
        }
        if(operator.getId() != null){

            Operator operator1 = service.getById(operator.getId());
            Account account = accountService.getOne(new QueryWrapper<Account>().eq("operator_id", operator.getId()));
            if(!operator1.getThree().equals(operator.getThree())) {
                int i = account.getThree() + (operator.getThree() - operator1.getThree());
                account.setThree(Math.max(i, 0));
            }
            if(!operator1.getSeven().equals(operator.getSeven())) {
                int i = account.getSeven() + (operator.getSeven() - operator1.getSeven()) ;
                account.setSeven(Math.max(i, 0));
            }
            if(!operator1.getThirty().equals(operator.getThirty())) {
                int i = account.getThirty() + (operator.getThirty() - operator1.getThirty());
                account.setThirty(Math.max(i, 0));
            }
            accountService.updateById(account);

            operator.setUpdateBy(StpUtil.getLoginIdAsInt());
            operator.setUpdateTime(new Date());
            b = service.updateById(operator);
        }else{
            operator.setCreateBy(StpUtil.getLoginIdAsInt());
            operator.setCreateTime(new Date());
            operator.setUpdateBy(StpUtil.getLoginIdAsInt());
            operator.setUpdateTime(new Date());
            operator.setStatus(1);
            b = service.save(operator);

            //创建经销商账户
            Account account = new Account();
            account.setOperatorId(operator.getId());
            account.setBalance("0");
            account.setFreezeMoney("0");
            account.setCreateTime(new Date());
            account.setThree(operator.getThree());
            account.setSeven(operator.getSeven());
            account.setThirty(operator.getThirty());

            accountService.save(account);
        }
        return b ? Result.OK() : Result.FAILURE();
    }

    /**
     * @param operator
     * @return
     */
    @PutMapping("status")
    public Result status(@RequestBody Operator operator){
        Operator r = new Operator();
        r.setId(operator.getId());
        r.setStatus(operator.getStatus());
        boolean b = service.updateById(r);
        return b ? Result.OK() : Result.FAILURE();
    }

    /**
     * 获取商品配置
     * @param id
     * @return
     */
    @GetMapping("getConfig")
    public Result<List<Integer>>  getConfig(@RequestParam("id") Integer id){
        List<OperatorConfig> operatorConfigs = operatorConfigService.list(new QueryWrapper<OperatorConfig>().eq("operator_id", id));
        List<Integer> list = new ArrayList<>();
        for (OperatorConfig operatorConfig : operatorConfigs) {
            list.add(operatorConfig.getGoodsId());
        }
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(),list);
    }

    @PostMapping("saveConfig")
    public Result saveConfig(@RequestBody Operator operator ){
        operatorConfigService.remove(new QueryWrapper<OperatorConfig>().eq("operator_id",operator.getId()));
        OperatorConfig operatorConfig;
        List<OperatorConfig> list = new ArrayList<>();
        List<Integer> goodsIds = operator.getGoodsIds();
        for (Integer goodsId : goodsIds) {
            operatorConfig = new OperatorConfig();
            operatorConfig.setGoodsId(goodsId);
            operatorConfig.setOperatorId(operator.getId());
            operatorConfig.setCreateBy(StpUtil.getLoginIdAsInt());
            operatorConfig.setCreateTime(new Date());
            operatorConfig.setUpdateBy(StpUtil.getLoginIdAsInt());
            operatorConfig.setUpdateTime(new Date());
            list.add(operatorConfig);
        }
        boolean b = operatorConfigService.saveBatch(list);
        return b ? Result.OK() : Result.FAILURE();
    }
}
